const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')



const handleBlogRouter = (req, res) => {
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]
    const id = req.query.id
    // console.log(id)

    //获取列表
    if (method === "GET" && path === '/api/blog/list') {
        const author = req.query.author || ''
        const keyword = req.query.keyword || ''
        // const listData = getList(author, keyword)
        // return new SuccessModel(listData)
        const result = getList(author, keyword)
        return result.then(listData => {
            return new SuccessModel(listData)
        })
    }

    //获取博客详情
    if (method === "GET" && path === '/api/blog/detail') {
        const result = getDetail(id)
        return result.then(detailData=>{
            return new SuccessModel(detailData)
        })
        // return new SuccessModel(detaiData)
    }

    //新建一遍博客
    if (method === "POST" && path === '/api/blog/new') {
        // const data = newBlog(req.body)
        // return new SuccessModel(data)

        req.body.author='iconMan'//假数据，开发完登录时再改成真实数据！
        const result=newBlog(req.body)
        return result.then(data=>{
            return new SuccessModel(data)
        })
    }

    //更新博客
    if (method === "POST" && path === "/api/blog/update") {

        const result = updateBlog(id, req.body)
        return result.then(data=>{
            if (data) {
                return new SuccessModel()
            } else {
                return new ErrorModel('更新博客失败')
            }
        })
    }

    //删除博客
    if (method === "POST" && path === "/api/blog/del") {
        const author='jeek'//假数据，开发完登录时再改成真实数据！
        const result = deleteBlog(id,author)
        return result.then(data=>{
            if (data) {
                console.log(data)
                return new SuccessModel()
            } else {
                return new ErrorModel("删除博客失败")
            }
        })
       

    }


}

module.exports = handleBlogRouter





